import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Register.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
    },
  ],
})
router.beforeEach(async (to, from) => {
  if (
      // ❗️ 避免无限重定向
      to.name !== "register" && to.name !== "login" &&
      // 检查用户是否已登录
      !localStorage.getItem('accessToken')
  ) {
    // 将用户重定向到登录页面
    return { name: "login" }
  }
})
export default router
